package com.qimou.iems.service.impl;

import com.qimou.iems.entity.AdminUser;
import com.qimou.iems.entity.PageArgs;
import com.qimou.iems.entity.PageList;
import com.qimou.iems.entity.UserRole;
import com.qimou.iems.exception.InterfaceCommonException;
import com.qimou.iems.mapper.IAdminUserMapper;
import com.qimou.iems.mapper.IUserRoleMapper;
import com.qimou.iems.service.IAdminUserService;
import com.qimou.iems.util.CommonUtil;
import com.qimou.iems.util.StatusConstant;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author Qimou Xie
 * @date 2018/4/14 16:12.
 **/
@Service
public class AdminUserServiceImpl implements IAdminUserService {

    @Resource
    private IAdminUserMapper adminUserMapper;
    @Resource
    private IUserRoleMapper userRoleMapper;

    @Override
    @Transactional
    public void save(AdminUser adminUser,String roleIds) {
        adminUserMapper.insert(adminUser);
        if(!CommonUtil.isEmpty(roleIds)){
            String[] roles = roleIds.split(",");
            List<UserRole> userRoles = new ArrayList<UserRole>();
            for (int i = 0; i < roles.length; i++) {
                UserRole ur = new UserRole();
                ur.setRoleId(Integer.valueOf(roles[i]));
                ur.setUserId(adminUser.getId());
                userRoles.add(ur);
            }
            if(userRoles.size() > 0){
                userRoleMapper.insert(userRoles);
            }
        }
    }

    @Override
    public AdminUser login(String account,String pwd) throws InterfaceCommonException {

        AdminUser adminUser = adminUserMapper.queryAdminUserByAccount(account);
        if(null == adminUser){
            throw new InterfaceCommonException(StatusConstant.OBJECT_NOT_EXIST,"帐号不存在");
        }
        if(StatusConstant.NO.equals(adminUser.getIsValid())){
            throw new InterfaceCommonException(StatusConstant.ACCOUNT_FROZEN,"帐号无效");
        }
        if(!pwd.equals(adminUser.getPwd())){
            throw new InterfaceCommonException(StatusConstant.Fail_CODE,"密码错误");
        }
        return adminUser;
    }

    @Override
    public void update(AdminUser adminUser) {
        adminUserMapper.update(adminUser);
    }


    @Override
    public AdminUser getAdminUser(String account) {
        return adminUserMapper.queryAdminUserByAccount(account);
    }

    @Override
    public PageList<AdminUser> getAdminUserList(Map<String, Object> map, PageArgs pageArgs) {
        List<AdminUser> adminUsers = new ArrayList<AdminUser>();
        int count = adminUserMapper.countAdminUser(map);
        if(count > 0){
            map.put("pageArgs",pageArgs);
            adminUsers = adminUserMapper.queryAdminUserList(map);
        }
        return new PageList<AdminUser>(adminUsers,count);
    }
}
